package cn.edu.tsinghua.ie.ieFunds.controller;


import cn.edu.tsinghua.ie.ieFunds.bean.system.Role;
import cn.edu.tsinghua.ie.ieFunds.service.RoleService;
import cn.edu.tsinghua.ie.ieFunds.service.UserService;
import cn.edu.tsinghua.ie.ieFunds.bean.system.HttpResult;
import cn.edu.tsinghua.ie.ieFunds.bean.system.ResultCode;
import cn.edu.tsinghua.ie.ieFunds.bean.system.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class SystemController {

    public static int MIN_USERNAME = 6;

    public static int MAX_USERNAME = 16;

    public static int MIN_PASSWORD = 6;

    public static int MAX_PASSWORD = 16;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping(value = "register", method = RequestMethod.POST)
    public HttpResult register(String username, String password, String retypePassword) {
        //TODO limit and verify
        User user = userService.getUserByUsername(username);
        if (user != null) {
            return new HttpResult(ResultCode.USERNAME_EXIST_ERROR, "用户名已存在");
        }
        if (password.compareTo(retypePassword) != 0) {
            return new HttpResult(ResultCode.PASSWORD_ERROR, "用户名已存在");
        }
        User registerUser = new User();
        registerUser.setUsername(username);
        registerUser.setPassword(new BCryptPasswordEncoder().encode(password));
        List<Role> roleList = new ArrayList<>();
        roleList.add(roleService.getRoleById(Role.FUNDS_MANAGER));
        registerUser.setRoles(roleList);
        userService.addUser(registerUser);
        return new HttpResult(ResultCode.NO_ERROR);
    }
}
